<template>
  <ContentWrap v-loading="formLoading">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基础信息" name="info">
        <InfoForm
          ref="infoRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
        <SkuForm ref="skuRef" :is-detail="isDetail" :propFormData="formData" />
      </el-tab-pane>

      <el-tab-pane label="付费会员详情" name="description">
        <DescriptionForm
          ref="descriptionRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
    </el-tabs>
    <el-form>
      <el-form-item style="float: right">
        <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as ProductSpuApi from '@/api/mall/product/spu'
import InfoForm from './InfoForm.vue'
import SkuForm from './SkuForm.vue'
import DescriptionForm from '@/views/mall/product/spu/form/DescriptionForm.vue'
import { convertToInteger, floatToFixed2, formatToFraction } from '@/utils'

defineOptions({ name: 'ProductSpuPaidMemberAdd' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { params, name } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('info') // Tag 激活的窗口
const isDetail = ref(false) // 是否查看详情
const infoRef = ref() // 商品信息 Ref
const skuRef = ref() // 商品规格 Ref
const descriptionRef = ref() // 商品详情 Ref
// SPU 表单数据
const formData = ref<ProductSpuApi.Spu>({
  spuType: 5,
  spuName: '', //付费会员名称
  picUrl: '', // 付费会员等级图标
  imgOblongUrl: '', //付费会员背景图
  spuId: undefined,
  isOpen: false, //是否开启
  salesChannel: [], //启用渠道
  authorizedTenant: [], //门店
  authorizedMallTenant: [], //商城
  salesOnlineChannel: [], // 线上商品销售渠道
  protocolId: undefined, //付费会员协议
  sort: 0,
  specType: true, // 商品规格

  skus: [
    {
      price: 0, // 商品价格 零售价
      picUrl: '', // 图片地址
      appointSkusCount: {}, //关联商品
      expiryDateUnit: 1,
      consumerMoney: undefined, //积分规则 消费多少元
      consumerPoints: undefined, //积分规则 积多少分
      rechargeMoney: undefined, //积分规则 充值多少元
      rechargePoints: undefined, //积分规则 积多少分
      memberMonthlyCouponType: 0, //付费会员|月赠送券设置类型 0 统一设置 1 单一设置
      bonusPoints: 0, //赠送积分
      isPostageCost: false, //是否包邮
      allDiscount: 0, //全部商品折扣
      appointTypeDiscount: {}, //指定商品类型
      appointSkusDiscount: {}, //储值卡 指定商品规则
      appointSkusCoupon: {}, //指定优惠券数量
      appointSkusBirthdayCoupon: {}, //指定生日券数量
      bonusDays: 1 //月赠送券日期

      // monthlyGiveCoupon: [
      //   {
      //     intoAccountDateDay: 1,
      //     skuCoupon: []
      //   }
      // ]
    }
  ],
  description: '' // 商品详情
})

/** 获得详情 */
const getDetail = async () => {
  if ('ProductSpuDetail' === name) {
    isDetail.value = true
  }
  const spuId = params.spuId as unknown as number
  if (spuId) {
    formLoading.value = true
    try {
      const res = (await ProductSpuApi.getSpu(spuId)) as ProductSpuApi.Spu
      res.skus?.forEach(async (item) => {
        if (isDetail.value) {
          item.price = floatToFixed2(item.price)
          item.consumerMoney = floatToFixed2(item.consumerMoney)
          item.rechargeMoney = floatToFixed2(item.rechargeMoney)
        } else {
          // 回显价格分转元
          item.price = formatToFraction(item.price)
          item.consumerMoney = formatToFraction(item.consumerMoney)
          item.rechargeMoney = formatToFraction(item.rechargeMoney)
        }
        item.typeDiscountGoods = [] as any
        console.log(item.appointTypeDiscount)

        Object.keys(item.appointTypeDiscount).map(function (key) {
          item.typeDiscountGoods!.push(Number(key))
        })

        item.tabsName = item.properties![0].valueName
        await unref(skuRef)?.handleTabsEdit(item.tabsName, 'add')

        // 将储值卡 商品类型折扣属性转成前端的格式
        // item.typeDiscount = JSON.parse(item.typeDiscount as string)
      })
      formData.value = res
    } finally {
      formLoading.value = false
    }
  } else {
    await unref(skuRef)?.initPropertyList()
  }
}

/** 提交按钮 */
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    // 校验各表单
    await unref(infoRef)?.validate()
    await unref(skuRef)?.validate()
    await unref(descriptionRef)?.validate()
    // 深拷贝一份, 这样最终 server 端不满足，不需要影响原始数据
    const deepCopyFormData = cloneDeep(unref(formData.value)) as ProductSpuApi.Spu
    deepCopyFormData.skus!.forEach((item) => {
      // 给sku name赋值
      item.spuName = deepCopyFormData.spuName
      // sku相关价格元转分
      item.price = convertToInteger(item.price)
      item.consumerMoney = convertToInteger(item.consumerMoney)
      item.rechargeMoney = convertToInteger(item.rechargeMoney)
    })

    // 校验都通过后提交表单
    const data = deepCopyFormData as ProductSpuApi.Spu
    const spuId = params.spuId as unknown as number
    if (!spuId) {
      await ProductSpuApi.createSpu(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductSpuApi.updateSpu(data)
      message.success(t('common.updateSuccess'))
    }
    close()
  } finally {
    formLoading.value = false
  }
}

/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'MemberPaidLevel' })
}

/** 初始化 */
onMounted(async () => {
  await getDetail()
})
</script>
